//
//  FoodPracticeViewController.m
//  FoodCorner
//
//  Created by Summer on 16/2/29.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "FoodPracticeViewController.h"
#import "ImageArrayModel.h"
#import "MainListModel.h"
#import "FoodPracticeCell.h"
#import "CategoryModel.h"
#import "HomeListViewController.h"
#import "HomeDataHelper.h"
#import "DataMemoryTools.h"
#import <UMSocial.h>
#import <SDAutoLayout/UITableView+SDAutoTableViewCellHeight.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <SDAutoLayout/UIView+SDAutoLayout.h>

#define APPKEY @"56dec37e67e58ea2cf002001"


@interface FoodPracticeViewController ()<UMSocialUIDelegate>
@property (nonatomic,strong) UIView *detailView;
@property (nonatomic,strong) NSMutableArray *foodStepArray;
@property (nonatomic,strong) UISwipeGestureRecognizer *leftSwipe;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UILabel *infoLab;
@property (nonatomic,strong) UILabel *ingredientsLab;
@property (nonatomic,strong) UILabel *burdenLab;
@end
static NSString *reuseIdentifier = @"stepID";
@implementation FoodPracticeViewController
//进行懒加载做法数组
-(NSMutableArray *)foodStepArray
{
    if (!_foodStepArray) {
        _foodStepArray =[NSMutableArray array];
    }
    return _foodStepArray;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    BOOL flag = [DataMemoryTools determineAnyModelIsHas:self.listModel];
    if (flag) {
        self.navigationItem.rightBarButtonItem.title = @"已收藏";
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[FoodPracticeCell class] forCellReuseIdentifier:reuseIdentifier];
    self.tableView.tableHeaderView = self.detailView;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self viewBlurEffect];
    UIBarButtonItem *leftBarButtonItem1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemStop)  target:self action:@selector(clickBackButtonAciotn)];
    UIBarButtonItem *leftBarButtonItem2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemAction) target:self action:@selector(shareAction)];
    self.navigationItem.leftBarButtonItems = @[leftBarButtonItem1,leftBarButtonItem2];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"收藏" style:(UIBarButtonItemStyleDone)  target:self action:@selector(collectionAction)];
    self.leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(clickBackButtonAciotn)];
    _leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [self judgeBelongToAnyModle];
}
- (void)clickBackButtonAciotn
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)collectionAction
{
    
    BOOL flag = [DataMemoryTools determineAnyModelIsHas:self.listModel];
    if (flag) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"此活动已被收藏" preferredStyle:(UIAlertControllerStyleAlert)];
        double delayInSeconds = 1.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self dismissViewControllerAnimated:YES completion:nil];
        });
            [self presentViewController:alert animated:YES completion:nil];
            NSLog(@"已经收藏了");
        
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"活动收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
        double delayInSeconds = 1.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            
            [DataMemoryTools addFavoriteFood:self.listModel];
            self.navigationItem.rightBarButtonItem.title = @"已收藏";
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
        });
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}
#pragma mark---分享按钮实现点击时间
- (void)shareAction
{
    
    NSString *shareText = [NSString stringWithFormat:@"我找到的一道非常好吃的菜品，有详细的步骤大家可以来看看"];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey: APPKEY
                                      shareText:shareText
                                     shareImage:[UIImage imageNamed:@"placeholder"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToWechatTimeline,nil]
                                       delegate:self];
}
//下面得到分享完成的回调
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    NSLog(@"didFinishGetUMSocialDataInViewController with response is %@",response);
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}

//菜品简介和好处、用料
- (UIView *)detailView{

    CGFloat margin = 10;
    if (!_detailView) {
        _detailView = [UIView new];
        //_detailView.backgroundColor = [UIColor redColor];
        _detailView.sd_layout
        .leftSpaceToView(self.view,margin)
        .rightSpaceToView(self.view,margin)
        .topSpaceToView(self.view,margin)
        .widthRatioToView(self.view,1)
        .heightIs(200);
        _imageView = [UIImageView new];
        _imageView.layer.masksToBounds = YES;
        _imageView.layer.cornerRadius = 80;
        [_detailView addSubview:_imageView];
        
        _imageView.sd_layout
        .leftSpaceToView(_detailView,margin)
        .topSpaceToView(_detailView,margin)
        .widthIs(160)
        .heightIs(160);
        _infoLab =[UILabel new];
        _infoLab.numberOfLines = 0;
        _infoLab.font = [UIFont systemFontOfSize:12.0];
        _infoLab.textColor = [UIColor grayColor];
        [_detailView addSubview:_infoLab];
        _ingredientsLab =[UILabel new];
        _ingredientsLab.numberOfLines = 0;
        _ingredientsLab.font = [UIFont systemFontOfSize:14.0];
        _ingredientsLab.textColor = [UIColor blackColor];
        _ingredientsLab.textAlignment = NSTextAlignmentRight;
        [_detailView addSubview:_ingredientsLab];
    
        //infoLab.backgroundColor = [UIColor redColor];
        _burdenLab =[UILabel new];
        _burdenLab.numberOfLines = 0;
        _burdenLab.font = [UIFont systemFontOfSize:12.0];
        _burdenLab.textColor = [UIColor blackColor];
        _burdenLab.textAlignment = NSTextAlignmentRight;
        [_detailView addSubview:_burdenLab];
        
        _infoLab.sd_layout
        .leftSpaceToView(_imageView,margin)
        .rightSpaceToView(_detailView,margin)
        .topSpaceToView(_detailView,margin)
        .heightRatioToView(_detailView,0.75);
        
        _ingredientsLab.sd_layout
        .leftSpaceToView(_detailView,margin)
        .rightEqualToView(_infoLab)
        .topSpaceToView(_infoLab,margin / 2)
        .autoHeightRatio(0);
        
        _burdenLab.sd_layout
        .leftEqualToView(_ingredientsLab)
        .rightEqualToView(_ingredientsLab)
        .topSpaceToView(_ingredientsLab,margin / 2)
        .autoHeightRatio(0);
    
    }
    return _detailView;
}

#pragma mark - 点击cell出现的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeListViewController *listView = [HomeListViewController new];
    UINavigationController *listNC = [[UINavigationController alloc]initWithRootViewController:listView];
    listView.dishMdoel = self.foodStepArray[indexPath.row];
    [self presentViewController:listNC animated:YES completion:nil];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return self.foodStepArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FoodPracticeCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
    // Configure the cell...
//    if (cell != nil) {
//        [cell.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
//    }
    ImageArrayModel *model = self.foodStepArray[indexPath.row];
    cell.model = model;
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ImageArrayModel *model = self.foodStepArray[indexPath.row];
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[FoodPracticeCell class] contentViewWidth:[self cellContentViewWith]];
}
- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 9.2) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

#pragma mark ----添加视图模糊效果，增加视觉效果
- (void)viewBlurEffect
{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    imageView.image = [UIImage imageNamed:@"placeholder"];
    //毛玻璃效果
    UIVisualEffectView *visualView =[[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:(UIBlurEffectStyleLight)]];
    visualView.alpha = 0.9;
    visualView.frame=[UIScreen mainScreen].bounds;
    
    [imageView addSubview:visualView];
    
    self.tableView.backgroundView = imageView;
    
    self.tableView.separatorEffect = [UIBlurEffect effectWithStyle:(UIBlurEffectStyleDark)];
}
#pragma mark ----对传进来的Model进行判断，判断是某个类型
///判断当前的Model对象，来讲Model对象添加到视图
- (void)judgeBelongToAnyModle
{
    if ([self.listModel isKindOfClass:[MainListModel class]]) {
        //[self.foodStepArray addObjectsFromArray:self.listModel.steps];
        NSArray *tempArray  = [[HomeDataHelper sharedHomeDataHelper] achieveDataFromArray:self.listModel.steps];
        [self.foodStepArray addObjectsFromArray:tempArray];
        [_imageView sd_setImageWithURL:[NSURL URLWithString:[self.listModel.albums lastObject]] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        _infoLab.text =self.listModel.imtro;
        _ingredientsLab.text = self.listModel.ingredients;
        _burdenLab.text = self.listModel.burden;
        self.title = self.listModel.title;
    }else
    {
        //[self.foodStepArray addObjectsFromArray:self.categoryModel.stepsArray];
        NSArray *tempArray  = [[HomeDataHelper sharedHomeDataHelper] achieveDataFromArray:self.categoryModel.steps];
        [self.foodStepArray addObjectsFromArray:tempArray];
        [_imageView sd_setImageWithURL:[NSURL URLWithString:[self.categoryModel.albums lastObject]] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        _infoLab.text =self.categoryModel.imtro;
        _ingredientsLab.text = self.categoryModel.ingredients;
        _burdenLab.text = self.categoryModel.burden;
        self.title = self.categoryModel.title;
    }
    
}


@end
